package com.fast.mybatis.freemarkerConfig;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
import org.springframework.util.ResourceUtils;

import java.io.File;

/**
 * @Author likaixuan
 * @Description
 * @Create Date  2018-09-14 22:29
 * @Version 1.0
 */
public class FreeMarkerConfig {

    private static FreeMarkerConfig single = new FreeMarkerConfig();

    private FreeMarkerConfig() {
    }

    //静态工厂方法
    public static FreeMarkerConfig getInstance() {
        return single;
    }

    public Template getDefinedTemplate(String templateName) throws Exception {

        //获取根目录
        File path = new File(ResourceUtils.getURL("classpath:").getPath());
        if (!path.exists()) path = new File("");

        Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
        String newPath = path.getAbsolutePath() + File.separator + "templates";

        //cfg.setDirectoryForTemplateLoading(new File("D:\\workspace\\fast-mybatis\\target\\classes\\templates"));

        cfg.setDirectoryForTemplateLoading(new File(newPath));
        cfg.setDefaultEncoding("UTF-8");
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        return cfg.getTemplate(templateName);
    }


}
